/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ohosannotations.ormlite.holder;

import static com.helger.jcodemodel.JExpr._null;
import static com.helger.jcodemodel.JMod.PRIVATE;

import java.util.HashMap;
import java.util.Map;

import javax.lang.model.type.TypeMirror;

import org.ohosannotations.helper.CaseHelper;
import org.ohosannotations.helper.ModelConstants;
import org.ohosannotations.holder.EComponentHolder;
import org.ohosannotations.holder.HasSimpleLifecycleMethods;
import org.ohosannotations.ormlite.helper.OrmLiteClasses;
import org.ohosannotations.plugin.PluginClassHolder;

import com.helger.jcodemodel.AbstractJClass;
import com.helger.jcodemodel.IJExpression;
import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JFieldVar;

/**
 * orm lite持有人
 *
 * @author dev
 * @since 2021-07-22
 */
public class OrmLiteHolder extends PluginClassHolder<EComponentHolder> {
    private Map<TypeMirror, JFieldVar> databaseHelperRefs = new HashMap<>();

    /**
     * orm lite持有人
     *
     * @param holder 持有人
     */
    public OrmLiteHolder(EComponentHolder holder) {
        super(holder);
    }

    /**
     * 得到数据库辅助裁判
     *
     * @param databaseHelperTypeMirror 数据库辅助类型镜子
     * @return {@link JFieldVar}
     */
    public JFieldVar getDatabaseHelperRef(TypeMirror databaseHelperTypeMirror) {
        JFieldVar databaseHelperRef = databaseHelperRefs.get(databaseHelperTypeMirror);
        if (databaseHelperRef == null) {
            databaseHelperRef = setDatabaseHelperRef(databaseHelperTypeMirror);
            injectReleaseAtEndLifecycle(databaseHelperRef);
        }
        return databaseHelperRef;
    }

    /**
     * 设置数据库辅助裁判
     *
     * @param databaseHelperTypeMirror 数据库辅助类型镜子
     * @return {@link JFieldVar}
     */
    private JFieldVar setDatabaseHelperRef(TypeMirror databaseHelperTypeMirror) {
        AbstractJClass databaseHelperClass = getJClass(databaseHelperTypeMirror.toString());
        String fieldName = CaseHelper.lowerCaseFirst(databaseHelperClass.name()) + ModelConstants.generationSuffix();
        JFieldVar databaseHelperRef = getGeneratedClass().field(PRIVATE, databaseHelperClass, fieldName);
        databaseHelperRefs.put(databaseHelperTypeMirror, databaseHelperRef);

        IJExpression dbHelperClass = databaseHelperClass.dotclass();
        holder().getInitBodyInjectionBlock().assign(databaseHelperRef,
            getJClass(OrmLiteClasses.OPEN_HELPER_MANAGER)
                .staticInvoke("getHelper").arg(holder().getContextRef()).arg(dbHelperClass));

        return databaseHelperRef;
    }

    /**
     * 注入释放在生命周期结束
     *
     * @param databaseHelperRef 数据库辅助裁判
     */
    private void injectReleaseAtEndLifecycle(JFieldVar databaseHelperRef) {
        if (holder() instanceof HasSimpleLifecycleMethods) {
            JBlock endLifecycleBody = ((HasSimpleLifecycleMethods) holder()).getEndLifecycleBeforeSuperBlock();

            endLifecycleBody.staticInvoke(getJClass(OrmLiteClasses.OPEN_HELPER_MANAGER), "releaseHelper");
            endLifecycleBody.assign(databaseHelperRef, _null());
        }
    }
}
